
import 'dart:io';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bind_terminal_info_confirm_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/scan_bind_terminal_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_scan_bind_terminal_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 扫码登录绑定页面
class TerminalScanPage extends StatefulWidget {
  final String gps;
  final String router;
  final String shid;
  ///路由名称
  static const String ROUTER = "TerminalScanPage";

  const TerminalScanPage({Key key, this.gps, this.router, this.shid}) : super(key: key);

  @override
  _TerminalScanPageState createState() => _TerminalScanPageState();

  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context,String gps, String router, {String shid}) {
    PermissionUtil.requestCamera((hasPermission)async{
      if(hasPermission){
        return RouterUtils.routeForFutureResult(
          context,
          TerminalScanPage(gps:gps, router: router, shid: shid,),
          routeName: TerminalScanPage.ROUTER,
        );
      }else{
        bool isSmartHome = UserRepository.getInstance().isSmartHomeCompany();
        if(isSmartHome){
          bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "请在设置界面给予App相机权限",
            cancelText: "取消",
            confirmText: "去授权",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }else{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "请在设置界面给予App相机权限",
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }

      }
    });

  }
}

class _TerminalScanPageState extends BaseState<TerminalScanPage> {
  Barcode result;
  QRViewController controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  NewTerminalListViewModel _viewModel;
  String _latestGps;
  VgLocation _locationPlugin;
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    }
    controller.resumeCamera();
  }

  @override
  void initState() {
    super.initState();
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((value) {
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        print("获取到了最新gps:" + value);
        if(value == _latestGps){
          print("定位的gps与当前一致，不执行刷新");
          return;
        }
      });
    });
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is LocationChangedEvent) {
        print("收到gps更新的:" + event?.gps);
        if(StringUtils.isNotEmpty(event?.gps??"")){
          if(event?.gps == _latestGps){
            print("更新的gps与当前一致，不执行刷新");
            return;
          }
          _latestGps = event?.gps;
        }
      }
    });

    _viewModel = NewTerminalListViewModel(this,gps: _latestGps);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: <Widget>[
          Container(child: _buildQrView(context)),
          Positioned(
            top: ScreenUtils.getStatusBarH(context),
            left: 0,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                Navigator.of(context).pop("");
              },
              child: _topLeftWidget(),
            ),
          ),
          Positioned(
            top: (ScreenUtils.screenH(context) - ScreenUtils.getBottomBarH(context)
                -ScreenUtils.getStatusBarH(context) - NAV_HEIGHT - 300)/2,
            left: 0,
            right: 0,
            child: Center(
              child: Text(
                "对准二维码，即可自动扫描",
                style: TextStyle(
                  color: const Color(0xFFD0E0F7),
                ),
              ),
            ),
          ),

          Positioned(
            bottom: 50,
            left: 0,
            right: 0,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () async {
                await controller?.toggleFlash();
                setState(() {});
              },
              child: Center(
                child: Image.asset(
                  "images/icon_flash_light.png",
                  width: 50,
                ),
              ),
            ),
          ),

          // Expanded(
          //   flex: 1,
          //   child: FittedBox(
          //     fit: BoxFit.contain,
          //     child: Column(
          //       mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          //       children: <Widget>[
          //         if (result != null)
          //           Text(
          //               'Barcode Type: ${describeEnum(result.format)}   Data: ${result.code}')
          //         else
          //           Text('Scan a code'),
          //         Row(
          //           mainAxisAlignment: MainAxisAlignment.center,
          //           crossAxisAlignment: CrossAxisAlignment.center,
          //           children: <Widget>[
          //             Container(
          //               margin: EdgeInsets.all(8),
          //               child: FlatButton(
          //                   onPressed: () async {
          //                     await controller?.toggleFlash();
          //                     setState(() {});
          //                   },
          //                   child: FutureBuilder(
          //                     future: controller?.getFlashStatus(),
          //                     builder: (context, snapshot) {
          //                       return Text('Flash: ${snapshot.data}');
          //                     },
          //                   )),
          //             ),
          //             Container(
          //               margin: EdgeInsets.all(8),
          //               child: FlatButton(
          //                   onPressed: () async {
          //                     await controller?.flipCamera();
          //                     setState(() {});
          //                   },
          //                   child: FutureBuilder(
          //                     future: controller?.getCameraInfo(),
          //                     builder: (context, snapshot) {
          //                       if (snapshot.data != null) {
          //                         return Text(
          //                             'Camera facing ${describeEnum(snapshot.data)}');
          //                       } else {
          //                         return Text('loading');
          //                       }
          //                     },
          //                   )),
          //             )
          //           ],
          //         ),
          //         Row(
          //           mainAxisAlignment: MainAxisAlignment.center,
          //           crossAxisAlignment: CrossAxisAlignment.center,
          //           children: <Widget>[
          //             Container(
          //               margin: EdgeInsets.all(8),
          //               child: FlatButton(
          //                 onPressed: () async {
          //                   await controller?.pauseCamera();
          //                 },
          //                 child: Text('pause', style: TextStyle(fontSize: 20)),
          //               ),
          //             ),
          //             Container(
          //               margin: EdgeInsets.all(8),
          //               child: FlatButton(
          //                 onPressed: () async {
          //                   await controller?.resumeCamera();
          //                 },
          //                 child: Text('resume', style: TextStyle(fontSize: 20)),
          //               ),
          //             )
          //           ],
          //         ),
          //       ],
          //     ),
          //   ),
          // )
        ],
      ),
    );
  }

  Widget _topLeftWidget(){
    return ClickAnimateWidget(
      child: Container(
        width: 40,
        height: 44,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 15.6),
        child: Image.asset(
          "images/top_bar_back_ico.png",
          width: 9,
          color: VgColors.INPUT_BG_COLOR,
        ),
      ),
      scale: 1.4,
      onClick: () {
        // VgNavigatorUtils.pop(context);
        FocusScope.of(context).requestFocus(FocusNode());
        Navigator.of(context).maybePop();
      },
    );
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    // var scanArea = (MediaQuery.of(context).size.width < 400 ||
    //     MediaQuery.of(context).size.height < 400)
    //     ? 150.0
    //     : 300.0;
    var scanArea = 300.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor:Color(0xFF1890FF),
          borderRadius: 0,
          borderLength: 30,
          borderWidth: 4,
          cutOutSize: scanArea),
      onPermissionSet: _onPermissionSet,
    );
  }

  void _onPermissionSet(QRViewController controller, bool permission){
    if(!permission){
      RouterUtils.pop(context);
      VgToastUtils.toast(context, "请打开相机权限");
    }
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) async{
      setState(() {
        if("00" == _viewModel.scanValueNotifier.value){
          return;
        }
        result = scanData;
        String code = result.code;
        print("scan result:" + code);
        if(!code.contains("?hsn=")){
          _viewModel.scanValueNotifier.value = "00";
          VgToastUtils.toast(context, "请先在出厂检测中心扫码，完成出厂检测工作。");
          Future.delayed(Duration(milliseconds: 2000),(){
            _viewModel.scanValueNotifier.value = "01";
          });
          return;
        }
        String hsn = code.substring(code.indexOf("?hsn=")+5, code.length);
        print("scan hsn:" + hsn);
        // ScanBindTerminalPage.navigatorPush(context, widget?.gps);
        _viewModel.scanLoginNew(context, hsn, (data) async {
          if("00" == data?.have){
            _viewModel.scanThenOperations(hsn, "13");
            RouterUtils.pop(context, result: true);
          }else if("02" == data?.have){
            //跳转到绑定确认的页面
            _viewModel.scanThenOperations(hsn, "14");
            dynamic result = await RouterUtils.pushAndPop(context,
                BindTerminalInfoConfirmPage(hsn: hsn,
                  defaultName: (data?.terName??"终端显示屏1"),
                  defaultPosition: (data?.position??"请选择"), router: widget?.router,), result: true);
            if(result == null){
              _viewModel.exitBindTerminal(hsn);
            }
          }else{
            RouterUtils.pop(context, result: true);
            if(UserRepository.getInstance().isSmartHomeCompany()){
              SmartHomeScanBindTerminalPage.navigatorPush(context, _latestGps, data, hsn, shid: widget?.shid??"");
            }else{
              ScanBindTerminalPage.navigatorPush(context, _latestGps, data, hsn);
            }

          }
        });
      });
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}

